package com.blue.gateway.paycore;

import com.blue.gateway.annotation.Channel;
import com.blue.gateway.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author xiaoyiming 
 * @date 2020/5/3 15:36 
 * @depiction 为@Channel 注解的类注入到对象中,并且指定别名
 */
@Slf4j
@Component
public class ChannelServiceRegistry implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanFactory) throws BeansException {
        log.info("postProcessBeanDefinitionRegistry init bean begin...");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        log.info("postProcessBeanFactory init bean begin...");

        String[] beans = beanFactory.getBeanNamesForAnnotation(Channel.class);
        if (beans.length > 0) {
            for (String bean : beans) {
                Class<?> cls = beanFactory.getType(bean);
                Channel channelService = cls.getAnnotation(Channel.class);

                // 获取被@Channel注解标记的服务类，进行注册别名,如:wxPayService
                String payChannel = channelService.PayChannel().getPayChannelValue();
                String serviceChannel = channelService.ServiceChannel().getValue();
                String beanName = payChannel + serviceChannel + Constants.BEAN_SERVICE_SUFFIX;

                //注册别名到容器
                if (!beanFactory.containsBeanDefinition(beanName)) {
                    log.info("register custom bean, beanName is {}", beanName);
                    beanFactory.registerAlias(bean, beanName);
                }
            }
        }
        log.info("postProcessBeanFactory init bean end...");
    }
}
